<template>
  <h3>登录</h3>
  <van-form @submit="handleLogin">
    <van-cell-group inset>
      <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]" />
      <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]" />
    </van-cell-group>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>
  </van-form>
  <p class="reg" @click="reg">立即注册</p>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import axios from '../utils/http';
import { userInfo } from '../types/login'
import { useRouter } from 'vue-router';
const router = useRouter()
const password = ref('')
const username = ref('')
const token = ref('')
const loginOutStatus = ref()
const loginOutMessage = ref('')
const onSubmit = async () => {
    const res = await axios.post<userInfo>('users/login', {
      userpwd: password.value,
      username: username.value
    })
    loginOutStatus.value = res.status
    loginOutMessage.value = res.message
    token.value = res.token
    console.log(res)
  };
const reg = ():void =>{
  router.push('/reg')
}
const userRegex = /^[a-zA-Z0-9]{6,12}$/;
const psdRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/
const handleLogin = async () => {
    if (!userRegex.test(username.value)) {
        alert('用户名输入格式不正确！');
        return;
    }
    if (!psdRegex.test(password.value)) {
        alert('输入的密码格式不正确！');
        return;
    }
    await onSubmit()
    if (loginOutStatus.value === 200) {
        alert('登录成功！');
        router.push('/del')
        localStorage.setItem('token', token.value)
    } else {
        alert(`${loginOutMessage.value}`);
    }
}

</script>

<style>
h3 {
  text-align: center;
  line-height: 50px;
  background-color: #1989fa;
  color: white;
}

.reg {
  display: flex;
  justify-content: end;
  margin-right: 15px;
  color: #1989fa;
}
</style>